package com.free.framework.base;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 李炳南
 * @date 2017/3/31
 */
public class BaseFragmentPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener{

    private List<Fragment> datas;

    private ViewPager viewPager;

    private RadioGroup group;

    private List<RadioButton>buttons;

    private OnPageSelected pageSelected;

    private int position;

    public BaseFragmentPagerAdapter(FragmentManager fm, List<Fragment> datas, ViewPager viewPager){
        this(fm,datas,viewPager,null);
    }

    public BaseFragmentPagerAdapter(FragmentManager fm, List<Fragment> datas, ViewPager viewPager, RadioGroup group) {
        super(fm);
        this.datas = datas == null ? new ArrayList<Fragment>() : datas;
        this.viewPager = viewPager;
        this.group = group;
        init();
    }


    private void init(){
        viewPager.setOnPageChangeListener(this);
        buttons = new ArrayList<>();
        int count = group.getChildCount();
        for(int i = 0 ; i < count ; i++){
            View view = group.getChildAt(i);
            if(view instanceof RadioButton){
                final int finalI = i;
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.setCurrentItem(finalI);
                    }
                });
                buttons.add((RadioButton) view);
            }
        }
        viewPager.setAdapter(this);
    }

    @Override
    public Fragment getItem(int position) {
        return datas.get(position);
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        this.position = position;
        if(position > buttons.size() - 1){
            return;
        }
        buttons.get(position).setChecked(true);

        if(pageSelected!=null){
            pageSelected.onPageSelected(position);
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public int getPosition() {
        return position;
    }

    public void setOnPageSelected(OnPageSelected pageSelected) {
        this.pageSelected = pageSelected;
    }

    public interface OnPageSelected{
       void onPageSelected(int position);
    }
}
